import React, { PropsWithChildren, useEffect } from 'react';

import { AuthApi } from '@/entities/auth/api';
import { setCheckAuth, setInAuth, signOut } from '@/entities/auth/model/actions';
import { getIsAuth, getUserId } from '@/entities/auth/model/selectors';
import { editProfile, getProfile, getUniqueAvatarList } from '@/entities/profile/model/actions';
import { getAvatarList, getUserProfile, getUserProfileState } from '@/entities/profile/model/selectors';
import { storage } from '@/shared/lib/storage';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { jwtDecode } from 'jwt-decode';

const AuthApiService = new AuthApi();

export const AuthProvider = ({ children }: PropsWithChildren) => {
  const dispatch = useAppDispatch();
  const isAuth = useAppSelector(getIsAuth);
  const profile = useAppSelector(getUserProfile);
  const profileState = useAppSelector(getUserProfileState);
  const userId = useAppSelector(getUserId);
  const avatarList = useAppSelector(getAvatarList);

  useEffect(() => {
    const accessToken = storage.getAccessToken();
    if (accessToken) {
      const decodedToken: {
        email?: string;
        exp: number;
        iat: string;
        shi: any[];
        sub: number;
      } = jwtDecode(accessToken);
      dispatch(setCheckAuth({ userId: decodedToken.sub, email: decodedToken?.email, expiresIn: decodedToken.exp }));
      if (decodedToken?.email) {
        localStorage.setItem('authEmail', decodedToken?.email);
      }
    } else {
      dispatch(setInAuth());
    }
  }, []);

  useEffect(() => {
    if (userId) {
      AuthApiService.updateLastActivity(userId as number);
    }
  }, [userId]);

  useEffect(() => {
    if (!isAuth || !userId) {
      return;
    }
    Promise.allSettled([dispatch(getUniqueAvatarList()), dispatch(getProfile(userId))]).then(() => {
      if (profile?.avatar === null && avatarList.length > 0) {
        const submitData = {
          avatar: avatarList[0].file,
        };
        dispatch(
          editProfile({
            id: userId as number,
            profile: submitData,
          }),
        );
      }
      if (profileState.error) {
        dispatch(signOut());
      }
    });
  }, [isAuth, userId, profile.avatar]);

  return <>{children}</>;
};
